# coding=utf-8
# @Time   : 2023/11/26
# @Author : wangjl
# @Email  : 1975039138@qq.com
import json
import os

CONFIG_PATH = "./config.json"


class SchedulerConfig(object):
    def __init__(self, config_path=CONFIG_PATH):
        self.config_path = config_path
        self._config = None
        self._init_config()

    def _init_config(self):
        if os.path.exists(self.config_path):
            with open(self.config_path, "r") as fp:
                print(f"## read config from {self.config_path}")
                self._config = json.load(fp)
        else:
            self._config = {}

    def set(self, conf: dict):
        for k, v in conf.items():
            self._config[k] = v

    def get(self, k):
        return self._config.get(k, False)

    def close(self):
        parent_dir = os.path.dirname(self.config_path)
        os.makedirs(parent_dir, exist_ok=True)
        with open(self.config_path, "w") as fp:
            print(f"## write config to {self.config_path}")
            json.dump(self._config, fp)

    @classmethod
    def from_path(cls, config_path):
        return cls(config_path)
